from alipay import AliPay
from django.shortcuts import redirect
from django.urls import reverse

from shopper.models import OrderInfos

# 支付宝公钥,用于验证支付回调签名
alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi67NE+osKHplQ1BwIbh1UZP0PmXgbX5kKLQg0hnNRcQerHNR76iF9BaFI3pwN+Ya9uSKbweo1fXWF4Gl4WQtold1HDr7QodYtpZpRFu6l112re3Y9pAbXat03MPNTto8oy3TcoOT1HR2M9VV/QPLdX0i6TWrjqjgdRz4ippi/IdjNI2NzmGF7Ete65gEEKalVFspu/q1I+SSVOXAF7ZKK1brYwBeBT1t6krgMxptHPLqMpHx3/apR26HSLEHom12VZKhg+0T3U5OjTt0+LFgbHctQzvorGCDjYkzbK/VgNLJifTpEvN/g3Ic0vh0QJTJmrsSnqOQDAVE0Q5NAJKMZwIDAQAB
-----END PUBLIC KEY-----"""

#应用私钥,用于生成支付签名
app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAkigZp2iEgks78XPelpFZHMC1TZQLjM5dc+ey6mth0Wiayj68p/uBEnt+L2DjfZgotxm+MLopqvgeW+3g0WCgnV35cIyhTDNMBsmVvBZaavELH5oh+5HEifJNXZDk8Tg/ralBJ0v/ww5uMSaaJgzN3Kws671gByXUZkYhKDLB4XHeGWDQ4OsqGc/rZC+0HRTHjeN0f9zy8tx6zvpzgFICVIRMKYqBn6RCz3lcHpzA1mmJLT9hcRRadOB/XhsDyk72jY/kq+8n8uOCiTbYSqkRLydxKj1StCJjtLSQn+dtONkX5ZSBw6qf6hs+87v185uUV2/KoYMXcCWL2Qk14f2RuQIDAQABAoIBAFtF3Zd1JuMzVpDXulavGEZjdhWncXsSWLwMIuhP/PtIZvoMKcaBwr4nDstJp2eEgVCvK93ENEdHwbXJHQ/EVylPSXnm6MfsdPr8Ip0eHIMSWs72c2hmRKWdAoF+/epCJUovG7gNtwA538ikAbnnXxwDDd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EY-----"""

def get_pay(out_trade_no, total_amount, return_url):
    """
    生成支付宝的支付链接
    :param out_trade_no: 商户订单号
    :param total_amount: 支付金额
    :param return_url: 支付成功后的回调URL地址
    :return: 支付宝支付页面URL
    """
    # 初始化支付宝SDK实例
    alipay = AliPay(
        # 自己的支付宝应用ID，沙箱环境的
        appid='9021000150645395',
        # 异步通知地址，None表示使用默认
        app_notify_url=None,
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        # 签名算法
        sign_type='RSA2'
    )

    # 生成支付宝页面支付请求参数
    order_string = alipay.api_alipay_trade_page_pay(
        # 商户的订单号，唯一，建议使用时间戳+随机数生成
        out_trade_no=out_trade_no,
        # 支付金额，转换为字符串主要是为了避免精度问题
        total_amount=str(total_amount),
        # 订单的标题
        subject='测试',
        # 支付成功后，同步回调地址
        return_url=return_url + "?t=" + out_trade_no,
        # 支付成功后的异步通知地址
        notify_url=return_url + "?t=" + out_trade_no,
    )
    # 拼接支付宝网关URL，生成一个可以访问的支付链接
    return "https://openapi-sandbox.dl.alipaydev.com/gateway.do?" + order_string

def payCallbackView(request):
    """
    处理支付回调逻辑，可以做一些验证支付结果等操作
    """
    payTime = request.session.get('payTime', '')
    if payTime:
        payInfo = request.session.get('payInfo', '')
        if payInfo:
            OrderInfos.objects.create(**payInfo)
            # 删除session中的信息
            del request.session['payInfo']
            del request.session['payTime']
    # 跳转个人中心
    return redirect(reverse('shopper:shopper'))